package dch.persistent.admin.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import dch.db.DataBaseDao;
import dch.db.DataBaseImpl;
import dch.entity.Video;
import dch.persistent.admin.dao.VideoDao;

public class VideoDaoImpl implements VideoDao {

	private Connection conn=null;
	private PreparedStatement pstmt=null;
	private ResultSet rs=null;
	private DataBaseDao db=new DataBaseImpl();
	
	private Video video =null;
	
	public VideoDaoImpl(){
		conn=db.getConnection();
	}
	
	public int insert(Video video,int albumid){
		int temp=0;
		try{
			pstmt=conn.prepareStatement("insert into video(title,videopath,albumid) values(?,?,?)");
			pstmt.setString(1,video.getTitle());
			pstmt.setString(2,video.getVideopath());
			pstmt.setInt(3,albumid);
			temp=pstmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}
		return temp;
	}
	
	public void delete(int id){
		try{
			pstmt=conn.prepareStatement("delete from video where videoid=?");
			pstmt.setInt(1,id);
			pstmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void update(Video video){
		try{
			pstmt=conn.prepareStatement("update video set title=?,videopath=? where videoid=?");
			pstmt.setString(1,video.getTitle());
			pstmt.setString(2,video.getVideopath());
			pstmt.setInt(3,video.getVideoid());
			pstmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public Video queryById(int id){
		video=new Video();
		try{
			pstmt=conn.prepareStatement("select v.videoid,v.title,v.videopath,v.publishtime,a.albumname " +
					"from video v left join album a on v.albumid=a.albumid where v.videoid=?");
			pstmt.setInt(1,id);
			rs=pstmt.executeQuery();
			while(rs.next()){
				video.setVideoid(rs.getInt("v.videoid"));
				video.setTitle(rs.getString("v.title"));
				video.setVideopath(rs.getString("v.videopath"));
				video.setPublishtime(rs.getTimestamp("v.publishtime"));
				video.getAlbum().setAlbumname(rs.getString("a.albumname"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return video;
	}

	@Override
	public void close() {
		try{
			if(null!=rs)
				rs.close();
			if(null!=pstmt)
				pstmt.close();
			if(null!=conn)
				conn.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
}
